package com.pai4j.message.aggregation;

import com.pai4j.message.model.MessageContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 时间窗口聚合策略
 * 在固定时间窗口内聚合消息
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
@Component
public class TimeWindowAggregationStrategy implements AggregationStrategy {

    @Override
    public AggregatedMessage aggregate(List<MessageContext> contexts) {
        if (contexts == null || contexts.isEmpty()) {
            return null;
        }

        // 获取第一条消息作为基准
        MessageContext first = contexts.get(0);
        
        AggregatedMessage aggregated = AggregatedMessage.builder()
                .aggregatedId(generateAggregatedId())
                .messageType(first.getMessageDTO().getClass().getSimpleName())
                .receiverId(first.getReceiverId())
                .aggregateCount(contexts.size())
                .startTime(LocalDateTime.now())
                .endTime(LocalDateTime.now())
                .createTime(LocalDateTime.now())
                .sent(false)
                .build();

        // 设置资源信息
        if (first.getResourceInfo() != null) {
            aggregated.setResourceId(first.getResourceInfo().getResourceId());
            aggregated.setResourceType(first.getResourceInfo().getResourceType());
        }

        // 收集所有发送者
        for (MessageContext context : contexts) {
            String senderId = context.getSenderId();
            String senderName = getSenderName(context);
            aggregated.addSender(senderId, senderName);
        }

        // 生成聚合内容
        String resourceTitle = first.getResourceInfo() != null ? 
                first.getResourceInfo().getTitle() : null;
        aggregated.generateAggregatedContent(resourceTitle);

        log.debug("聚合消息生成: count={}, content={}", 
                aggregated.getAggregateCount(), aggregated.getAggregatedContent());

        return aggregated;
    }

    @Override
    public boolean shouldTrigger(int count, AggregationRule rule) {
        if (rule == null) {
            return false;
        }

        return count >= rule.getMinCount();
    }

    @Override
    public String getStrategyName() {
        return "time-window";
    }

    /**
     * 获取发送者名称
     */
    private String getSenderName(MessageContext context) {
        // 尝试从扩展数据获取
        Object name = context.getMetadata().get("senderName");
        if (name != null) {
            return name.toString();
        }

        // 使用senderId
        return context.getSenderId();
    }

    /**
     * 生成聚合消息ID
     */
    private String generateAggregatedId() {
        return "AGG-" + System.currentTimeMillis() + "-" + 
               (int)(Math.random() * 10000);
    }
}

